package com.regan.test;

import cn.hutool.core.date.DateUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlRunner;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据库便捷操作
 *
 * @author zhangby
 * @date 2017/9/21 15:26
 */
public class DBUtils {

    private static SqlRunner sqlRunner = null;

    /**
     * 创建hutool dbUtils
     */
    private static synchronized void syncInit() {
        if (sqlRunner == null) {
            Prop prop = PropKit.use("db_config.properties");
            DataSource ds = new SimpleDataSource(
                    prop.get("jdbcUrl"),
                    prop.get("user"),
                    prop.get("password")
            );
            sqlRunner = SqlRunner.create(ds);
        }
    }

    public static SqlRunner getInstance() {
        if (sqlRunner == null) {
            syncInit();
        }
        return sqlRunner;
    }

    /**
     * 查询
     * @param args
     */
    public static void main(String[] args) throws SQLException {
        SqlRunner runner = getInstance();
        //查询
        List<Entity> list = runner.find(
                Entity.create("user").set("name", "unitTestUser"));
        //更新
        runner.update(Entity.create("user")
                .set("name", "张三")
                .set("age", 66),Entity.create("user").set("id", "1"));
        //插入
        runner.insert(Entity.create("user")
                .set("name", "unitTestUser")
                .set("age", 66));
        //删除
        runner.del(Entity.create("user").set("name", "unitTestUser"));

        //直接写sql
        List<Entity> query = runner.query("SELECT * FROM user");
        runner.execute("update user set name=? where id=?","张三","1");
        runner.execute("insert into user(name) values(?)","张三");
        runner.execute("DELETE FROM user WHERE name = ?","张三");
    }

}
